#!/usr/bin/env python

import Image
import sys

import FuseStat
import Node

class Tree:
   def __init__(self, fileSystems):
      self.fileSystems = fileSystems
     
   def getChildren(self):
      n1 = Node.Node(".")
      n2 = Node.Node("..")
      return [n1, n2] + self.fileSystems
     
   def getChild(self, name):
      # Ignore the first 2, i.e. the '.' and '..' entries
      for e in self.getChildren()[2:]:
         if e.getName() == name:
            return e
      return None
     
   def getName(self):
      return '/'
     
   def getAttribs(self):
      return FuseStat.DirStat()

   def isDirectory(self):
      return True
      
   def __str__(self):
      return self.getName()
     
   def find(self, path):
      if path == '/':
         return self
      else:
         node = self
         if path[-1] == '/':
            path=path[:-1]
         elems = path[1:].split('/')
         for p in elems:
            if node is not None:
               node = node.getChild(p)

         if node is None:
            print "\t*** :" + path + ": not found."

         # Reached the end of the path, this is the right node.
         return node

def printTree(node, depth):
   print 3 * depth * " " + ":" + node.getName() + ":"
   for e in node.getChildren():
      if e.getName()[0] != '.':
         printTree(e, depth + 1)

def main(args):
   # Initialise the image
   image = Image.Image(args[1])
   
   fileSystems = image.getFileSystems()
   if len(fileSystems) == 0:
      print "Error, no file systems, nothing to show"
      return
     
   tree = Tree(fileSystems)
   
   printTree(tree, 0)
   
   print "----"
   paths = ["/FS2/C131074/UB40", "/FS2/C131074/Shakira", "/FS1/C6/Store-V1",
               "/FS2/C131074/U-Roy", "/FS2/C131074/U-Roy/Now", "/FS2", "/", "/FS2/C131074/U-Roy/Now", ]
   print len(paths)
   print "-----"
   
   for path in paths:
      e = tree.find(path)
      if e is None:
         print ":" + path + ": path does not exist"
      else:
         print "\t" +str(e.isDirectory())
         print "\t" +str(len(e.getChildren()))
         
   print "-----"
   printTree(tree, 0)
         

# Then starting with newer file systems, mark clusters, mark physical disk as done.
# Then onto older ones, noting that parts of the disk have been overwritten by the newer file systems.
     
if __name__ == '__main__':
   debug = False
   main(sys.argv)
